package com.dhnsoft.代码随想录.链表;

/**
 * ClassName: d05_19_删除链表的倒数第N个节点
 * Package: com.dhnsoft.代码随想录.链表
 * Description:
 *
 * @Author dhn
 * @Create 2024/3/11 10:24
 * @Version 1.0
 */
public class d05_19_删除链表的倒数第N个节点 {
    public static void main(String[] args) {
        LinkedNode singLinked = new LinkedNode();
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(4);
        ListNode l5 = new ListNode(5);
//        ListNode l4 = new ListNode(4);
        singLinked.add(l1);
        singLinked.add(l2);
        singLinked.add(l3);
        singLinked.add(l4);
        singLinked.add(l5);
        ListNode listNode = removeNthFromEnd(singLinked.getHead(), 2);
        System.out.println(listNode);
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        if(head==null){
            return null;
        }
        if(head.next==null&&n==1){
            return null;
        }
        int len = 0;
        ListNode newHead = new ListNode(-1);
        newHead.next = head;
        ListNode temp = newHead.next;
//        ListNode temp = head.next;
        while (temp!=null){
            len++;
            temp = temp.next;
        }
        ListNode newNode = newHead;
//        ListNode newNode = head;
        for (int i=0;i<len-n;i++){
            newNode = newNode.next;
        }
        newNode.next = newNode.next.next;

        return newHead.next;
//        return head;

    }
}
